package com.zoffy.ybuhelper.fragment;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.zoffy.ybuhelper.MyApplication;
import com.zoffy.ybuhelper.adapter.EatRecyclerAdapter;
import com.zoffy.ybuhelper.adapter.OriginRecyclerAdapter;
import com.zoffy.ybuhelper.dao.OriginDao;
import com.zoffy.ybuhelper.database.YBUDatabase;
import com.zoffy.ybuhelper.pojo.entity.Origin;

import java.util.ArrayList;
import java.util.List;

public class OriginControlFragment extends ItemControlFragment {
    private YBUDatabase YBUDatabase;
    private List<Origin> dataList;
    private OriginRecyclerAdapter adapter;
    private OriginDao originDao;

    public OriginControlFragment(String type, String topBarText) {
        super(type, topBarText);
    }

    @Override
    protected void dataInit() {
        dataList = new ArrayList<>();
        YBUDatabase = MyApplication.getInstance().getYBUDatabase();
        originDao = YBUDatabase.originDao();
        dataList = originDao.getAll();
    }

    @Override
    protected void showDelete() {
        adapter.changeCouldDelete();
    }

    @Override
    protected void adapterInit() {
        adapter=new OriginRecyclerAdapter(dataList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        adapter.setSetItemOnclick(new EatRecyclerAdapter.SetItemOnclick() {
            @Override
            public void onDeleteClick(int position) {
                Origin origin=(Origin) adapter.getDataListAt(position);
                int id=origin.getId();
                YBUDatabase.originDao().deleteById(id);
                adapter.deleteItem(position);
                adapter.notifyItemRemoved(position);
            }

            @Override
            public void onChangeClick(int position) {
                AddItemFragment childFragment=new AddItemFragment();
                Origin origin=(Origin) adapter.getItemAt(position);
                Bundle bundle=new Bundle();
                bundle.putString("type","change_origin");
                bundle.putInt("id",origin.getId());
                childFragment.setArguments(bundle);
                childFragment.show(fragmentManager,"add_item_dialog");
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void update() {
        dataList = originDao.getAll();
        adapterInit();

    }
}
